package org.mspring.mlog.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.mspring.mlog.service.exception.StorageException;
import org.mspring.mlog.utils.WebUtils;
import org.mspring.platform.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 储存服务
 *
 * @author Gao Youbo
 * @since 2012-9-7
 */
@Service
public class StorageService {

    private static final Logger log = LoggerFactory.getLogger(StorageService.class);

    public static final String DEFAULT_UPLOAD_DIRECTORY = "/uploads";
    private String uploadDirectory = DEFAULT_UPLOAD_DIRECTORY;

    /**
     * 上传文件
     *
     * @param filename
     * @param file
     * @return
     * @throws StorageException
     */
    public String put(String filename, File file) throws StorageException {
        if (StringUtils.isBlank(filename)) {
            throw new StorageException("filename is blank!");
        }
        if (file == null || !file.exists()) {
            throw new StorageException("file does not exists!");
        }
        File destFile = get(filename);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            FileUtils.copyFile(file, destFile);
        } catch (IOException e) {
            log.error("put file error!", e);
        }
        return getRelativePath(destFile);
    }

    /**
     * 上传
     *
     * @param filename
     * @param is
     * @return
     * @throws StorageException
     */
    public String put(String filename, InputStream is) throws StorageException {
        if (StringUtils.isBlank(filename)) {
            throw new StorageException("filename is blank!");
        }
        File destFile = get(filename);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            FileUtils.copyInputStreamToFile(is, destFile);
        } catch (IOException e) {
            log.error("put InputStream error!", e);
        }
        return getRelativePath(destFile);
    }

    /**
     * 删除
     *
     * @param filename
     */
    public void remove(String filename) {
        if (StringUtils.isBlank(filename)) {
            return;
        }
        File file = get(filename);
        if (file.isDirectory()) {
            log.warn("can't delete directory");
            return;
        }
        file.delete();
    }

    /**
     * 根据文件名称相对路径获取文件
     *
     * @param filename
     * @return
     */
    public File get(String filename) {
        StringBuilder sb = new StringBuilder();
        sb.append(WebUtils.getRealContextPath());
        sb.append(uploadDirectory).append(File.separator);
        sb.append(filename);
        return new File(sb.toString());
    }

    /**
     * 获取文件访问的URL
     *
     * @param filename
     * @return
     */
    public String getUrl(String filename) {
        StringBuilder sb = new StringBuilder();
        sb.append(uploadDirectory).append(filename);
        return sb.toString();
    }

    /**
     * 获取文件相对于uploadDirectory的路径
     *
     * @param file
     * @return
     */
    private String getRelativePath(File file) {
        String filename = file.getPath();
        filename = StringUtils.replace(filename, "\\", "/");
        while (StringUtils.indexOf(filename, "//") > 0) {
            filename = StringUtils.replace(filename, "//", "/");
        }

        String split = StringUtils.replace(uploadDirectory, "", "/");
        split = StringUtils.replace(split, "//", "/");

        String relativePath = StringUtils.substringAfter(filename, split);
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }
        return relativePath;
    }

    public void setUploadDirectory(String uploadDirectory) {
        this.uploadDirectory = uploadDirectory;
    }

}
